package com.nanfang51g3.ckz.ui.index;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.nanfang51g3.ckz.R;
import com.nanfang51g3.ckz.adapter.base.DividerItemDecoration;
import com.nanfang51g3.ckz.adapter.ext.IndexAdapter;
import com.nanfang51g3.ckz.adapter.listener.OnItemClickListener;
import com.nanfang51g3.ckz.adapter.listener.OnItemLongClickListener;
import com.nanfang51g3.ckz.application.CkzApplication;
import com.nanfang51g3.ckz.domain.IndexBean;
import com.nanfang51g3.ckz.domain.RightTypeBean;
import com.nanfang51g3.ckz.ui.base.IPresenter;
import com.nanfang51g3.ckz.ui.accounting.AccountingActivity;
import com.nanfang51g3.ckz.ui.base.Base2Activity;
import com.nanfang51g3.ckz.ui.login.LoginActivity;
import com.nanfang51g3.ckz.ui.me.MeActivity;
import com.nanfang51g3.ckz.ui.share.ShareTuiActivity;
import com.nanfang51g3.ckz.utils.AppManager;
import com.nanfang51g3.ckz.utils.EasyToast;
import com.nanfang51g3.ckz.utils.KLog;
import com.nanfang51g3.ckz.utils.SPUtil;
import com.nanfang51g3.ckz.widget.GlideCircleTransform;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * Created by Administrator on 2016/4/19.
 * * 版本1.0.0功能的类，已弃用[HomeIndexFragment代替]
 */
public class IndexActivity extends Base2Activity implements IndexContract.View {
    IndexContract.IndexActionsListener indexActionsListener;
    IndexAdapter indexAdapter;
    ArrayList<IndexBean> releaseInfoS = new ArrayList<>();
    @Bind(R.id.id_toolbar)
    Toolbar idToolbar;
    @Bind(R.id.index_recycler_view)
    RecyclerView indexRecyclerView;
    @Bind(R.id.index_ptr_frame)
    PtrClassicFrameLayout indexPtrFrame;
    @Bind(R.id.index_tv_title_city)
    TextView indexTvTitleCity;
    Drawable d;
    boolean more = false;
    int page = 1;
    int limit = 10;


    @Override
    public int getContentView() {
        return R.layout.index;
    }

    @Override
    public boolean isShowLeftIcon() {
        return true;
    }

    @Override
    public boolean isShowRightIcon() {
        return true;
    }

    @Override
    public int setLeftIcon() {
        return R.mipmap.ic_index_info;
    }

    @Override
    public int setRightIcon() {
        return R.mipmap.ic_index_money;
    }

    @Override
    public int showTitle() {
        return R.string.str_index;
    }

    @Override
    public void showProgress() {
        super.showPro(R.string.str_progress_index);
    }

    @Override
    public void dismissProgress() {
        super.dismissPro();

    }

    @Override
    public void showSuccess(List<IndexBean> remote, ArrayList<RightTypeBean> strings, boolean pullDown, String tName) {
        KLog.i("Evd", "showSuccess 1= " + remote.size());
        KLog.i("Evd", "showSuccess 2= " + releaseInfoS.size());
        if (more) {
            releaseInfoS.addAll(remote);
            indexAdapter.addList(releaseInfoS);
        } else {
            releaseInfoS.clear();
            releaseInfoS.addAll(remote);
            indexAdapter.addList(releaseInfoS);
        }
        KLog.i("Evd", "showSuccess 3= " + releaseInfoS.size());
    }


    @Override
    public void onClickLeft(View v) {
        boolean is_login = (boolean) SPUtil.get(this, "is_login", false);
        if (is_login) {
            startActivity(new Intent(this, MeActivity.class));

        } else {
            EasyToast.showShort(this, "你还未登录哦,请先登录");
            startActivity(new Intent(this, LoginActivity.class));
        }

    }

    @Override
    public IPresenter getPresenter() {
        return indexActionsListener;
    }

    @Override
    public void onClickRight(View v) {
        boolean is_login = (boolean) SPUtil.get(this, "is_login", false);
        if (is_login) {
            startActivity(new Intent(this, AccountingActivity.class));
        } else {
            EasyToast.showShort(this, "你还未登录哦,请先登录");
            startActivity(new Intent(this, LoginActivity.class));
        }
    }

    @Override
    public Context getContext() {
        return this;
    }


    @Override
    public void showLocationValue(final String city) {
        KLog.i("Evd", "位置改变：=" + city);
        KLog.i("Evd", indexTvTitleCity == null ? "indexTvTitleCity-1" : "indexTvTitleCity-0");
        if (indexTvTitleCity != null) {
            indexTvTitleCity.post(new Runnable() {
                @Override
                public void run() {
                    if (!TextUtils.isEmpty(city)) {
                        indexTvTitleCity.setVisibility(View.VISIBLE);
                        indexTvTitleCity.setText(city);
                    }
                }
            });
        }
    }

    @Override
    public void showMessage(String message, String tName) {
        EasyToast.showShort(this, message);
    }

    @Override
    public void onIntent() {
        super.onIntent();

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        KLog.i("Evd", "index-启动了");
        indexActionsListener = DaggerIndexContractComponent
                .builder()
                .appComponent(CkzApplication.getAppComponent())
                .indexPresenterModule(new IndexPresenterModule(this))
                .build().getIndexPresenter();
        indexPtrFrame.setLastUpdateTimeRelateObject(this);
        indexPtrFrame.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                // TODO Auto-generated method stub
                more = false;
                page = 1;
                /**
                 * 网络请求数据
                 * @see IndexPresenter#requestIndex(int, int, boolean)
                 */
                indexActionsListener.requestIndex(page, limit, true);
                indexPtrFrame.refreshComplete();
            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                // TODO Auto-generated method stub
                more = true;
                ++page;
                /**
                 * 网络请求数据
                 * @see IndexPresenter#requestIndex(int, int)
                 */
                indexActionsListener.requestIndex(page, limit, false);
                indexPtrFrame.refreshComplete();

            }


        });
        // the following are default settings
        indexPtrFrame.setResistance(1.7f);
        indexPtrFrame.setRatioOfHeaderHeightToRefresh(1.2f);
        indexPtrFrame.setDurationToClose(200);
        indexPtrFrame.setDurationToCloseHeader(1000);
        // default is false
        indexPtrFrame.setPullToRefresh(false);
        // default is true
        indexPtrFrame.setKeepHeaderWhenRefresh(true);

        indexAdapter = new IndexAdapter(releaseInfoS);
        indexAdapter.setActivity(this);
        indexAdapter.setOnItemClickListener(new OnItemClickListener<IndexBean>() {

            @Override
            public void onClick(View view, IndexBean item) {
                startActivity(new Intent(IndexActivity.this, ShareTuiActivity.class)
                        .putExtra("id_image_url", item.getImage())
                        .putExtra("id_price", item.getPrice() + "")
                        .putExtra("id_title", item.getImage_title())
                        .putExtra("id_content", item.getSummary())
                        .putExtra("id_url", "http://ckt.51g3.com/view.php?ad=" + item.getId()));
            }
        });

        indexAdapter.setOnItemLongClickListener(new OnItemLongClickListener<IndexBean>() {
            @Override
            public void onLongClick(View view, IndexBean item) {
            }
        });
        indexRecyclerView.setHasFixedSize(true);//固定大小
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        indexRecyclerView.setLayoutManager(linearLayoutManager);
        //间隔线条
        indexRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        indexRecyclerView.setAdapter(indexAdapter);
        /**
         * 网络请求数据
         * @see IndexPresenter#requestIndex(int, int)
         */
        indexActionsListener.requestIndex(page, limit, true);
        //初始化位置监听
        LocationServerListener listener = new LocationServerListener(this, indexActionsListener);
        /**
         * @see IndexPresenter#initLocation(Context, LocationServerListener)
         */
        indexActionsListener.initLocation(this, listener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean is_login = (boolean) SPUtil.get(this, "is_login", false);
        boolean is_avatar = (boolean) SPUtil.get(this, "is_avatar", false);
        if (is_login) {
            //定义临时变量,防止多次转换出现问题
            if (d != null) {
                KLog.i("TAG", "d!=null");
                if (is_avatar) {
                    String userPic = (String) SPUtil.get(this, "userpic", "");
                    Glide.with(this).load(userPic)
                            .asBitmap().transform(new GlideCircleTransform(this)).into(new SimpleTarget<Bitmap>(45, 45) {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), resource);
                            d = (Drawable) bitmapDrawable;
                            idToolbar.setNavigationIcon(d);

                        }
                    });
                } else {
                    idToolbar.setNavigationIcon(d);
                }
            } else {
                KLog.i("TAG", "d==null");
                String userPic = (String) SPUtil.get(this, "userpic", "");
                Glide.with(this).load(userPic)
                        .asBitmap().transform(new GlideCircleTransform(this)).into(new SimpleTarget<Bitmap>(45, 45) {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), resource);
                        d = (Drawable) bitmapDrawable;
                        idToolbar.setNavigationIcon(d);

                    }
                });
            }
        } else {
            KLog.i("TAG", "else");
            idToolbar.setNavigationIcon(R.mipmap.ic_index_info);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);//解除绑定，官方文档只对fragment做了解绑
    }

    private long exitTime = 0;

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            EasyToast.showShort(this, "再按一次,退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            AppManager.getAppManager().finishAllActivity();
        }
    }


}
